<?php

namespace App\Http\Controllers\Api;

use App\Http\Models\Medical;
use App\Http\Models\MemberDoctor;
use App\Models\InvitationCode;
use Carbon\Carbon;
use Dcat\Admin\Models\Administrator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

/**
 * 病例库
 *
 * @Author hechengwei
 * @email chichiooo@sina.com
 * @DateTime 2022-03-09
 */
class MedicalController extends BaseController
{

    public function getList(Request $request)
    {
        $rules = [
            'keywords' => ['required'],
            'page' => ['required'],
            'limit' => ['required'],
        ];

        $message = [
            'keywords.required' => '请输入关键字',
            'page.required' => '页码不能为空',
            'limit.required' => '限制条数不能为空',
        ];

        $payload = $request->only('keywords', 'page', 'limit');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        $model = new Medical();

        $list = $model->getMedicalByKeyWords((int) $payload['page'], (int) $payload['limit'], ['keywords' => $payload['keywords']], ['id', 'title', 'medical_history', 'author', 'created_at']);

        return success($list);
    }
    /**
     * 热门推荐
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-12-20
     * @return json
     */
    public function hotRecommend(Request $request)
    {
        $rules = [
            'page' => ['required'],
            'limit' => ['required'],
        ];

        $message = [
            'page.required' => '页码不能为空',
            'limit.required' => '限制条数不能为空',
        ];

        $payload = $request->only('page', 'limit');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        $model = new Medical();

        $list = $model->getHotRecommend((int) $payload['page'], (int) $payload['limit'], ['id', 'title', 'author']);

        return success($list);
    }


    /**
     * 根据活动ID获取热门推荐
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-02-02
     * @return json
     */
    public function hotRecommendByActivity(Request $request)
    {
        $rules = [
            'page' => ['required'],
            'limit' => ['required'],
            'act_id' => ['required'],
        ];

        $message = [
            'page.required' => '页码不能为空',
            'limit.required' => '限制条数不能为空',
            'act_id.required' => '缺少参数活动ID',
        ];

        $payload = $request->only('page', 'limit', 'act_id');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        $model = new Medical();
        $where['act_id'] = $payload['act_id'];
        $list = $model->getHotRecommendByActId($where, (int) $payload['page'], (int) $payload['limit'], ['id', 'title', 'author']);

        return success($list);
    }

    /**
     * 病例详情
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-12-20
     * @param Request $request
     * @return json
     */
    public function getDetail(Request $request)
    {
        $rules = [
            'id' => ['required'],
        ];

        $message = [
            'id.required' => 'id不能为空',
        ];

        $payload = $request->only('id');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        $where['id'] = $payload['id'];
        // $where['user_id'] = memberId();
        $detail = Medical::where($where)->select('*', 'attachments as attachments_data')->first();
        return success($detail);
    }

    /**
     * 删除病例
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-03-10
     * @param Request $request
     * @return json
     */
    public function delMedical(Request $request)
    {
        $rules = [
            'id' => ['required'],
        ];

        $message = [
            'id.required' => 'id不能为空',
        ];

        $payload = $request->only('id');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        $where['id'] = $payload['id'];

        $where['user_id'] = memberId();

        // $res = Medical::delOneSoft($where);
        $res = Medical::where($where)->delete();

        if ($res) {
            return success($res);
        } else {
            return fail_message('没有权限');
        }
    }

    /**
     * 添加修改病例
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-06-24
     * @param Request $request
     * @return json
     */
    public function createMedical(Request $request)
    {
        // 邀请码
        $payload = $request->only([
            'id',
            'act_id',
            'name',
            'sex',
            'age',
            // hp检查时间
            'hp_check_date',
            // hp检查方法单选
            'hp_check_method',
            // hp检查方法录入
            'hp_check_method_input',
            // hp检查结果
            'hp_check_result',
            // 疾病诊断
            'disease_diagnosis',
            // 疾病诊断输入
            'disease_diagnosis_input',
            // 胃镜诊断单选
            'gastroscopy_diagnosis',
            // 胃镜诊断输入
            'gastroscopy_diagnosis_input',
            // 病理诊断单选
            'case_diagnosis',
            // 病理诊断输入
            'case_diagnosis_input',
            // 既往hp感染治疗史单选
            'hp_treatment_history',
            // 既往hp感染治疗史输入
            'hp_treatment_history_input',
            // 用药记录复选框
            'medical_record_checkbox',
            // ppi输入记录
            'ppi_input',
            // ppi用法用量
            'ppi_usage_dosage',
            // 铋剂输入
            'bismuth_input',
            // 铋剂用法用量
            'bismuth_usage_dosage',
            // 抗生素1输入
            'antibiotic1_input',
            // 抗生素1用法用量
            'antibiotic1_usage_dosage',
            // 抗生素2输入
            'antibiotic2_input',
            // 抗生素2用法用量
            'antibiotic2_usage_dosage',
            // 荜铃胃痛颗粒输入
            'biling_granules_input',
            // 荜铃胃痛颗粒用法用量
            'biling_granules_usage_dosage',
            // 开始服药时间
            'start_taking_medicine',
            // 停止服药时间
            'stop_taking_medicine',
            // 是否调整用药方案
            'adjust_medication',
            // 调整药物原因
            'adjust_medication_reason',
            // 治疗前-程度-上腹痛
            'pre_degree_ep_pain',
            // 治疗前-程度-餐后饱张
            'pre_degree_after_meal_satiety',
            //  治疗前-程度-早饱
            'pre_degree_premature_satiety',
            // 治疗前-程度-上腹烧灼
            'pre_degree_burn_upper_abdomen',
            // 治疗前-程度-总分
            'pre_degree_amount',
            // 治疗前-频率-上腹痛
            'pre_frequency_ep_pain',
            //治疗前-频率-餐后饱张
            'pre_frequency_after_meal_satiety',
            //治疗前-频率-早饱
            'pre_frequency_premature_satiety',
            //治疗前-频率-上腹烧灼
            'pre_frequency_burn_upper_abdomen',
            //治疗前-频率-总分
            'pre_frequency_amount',
            //其他-泛酸
            'pre_other_acid_regurgitation',
            //其他-烧心
            'pre_other_heartburn',
            //其他-大便
            'pre_other_shit',
            //其他-疲乏
            'pre_other_fatigued',
            //其他-睡眠差
            'pre_other_poor_sleep',
            //其他-烦躁易怒
            'pre_other_irritability',
            //其他-焦虑
            'pre_other_anxiety',
            // 其他-抑郁
            'pre_other_depressed',
            //治疗后检查时间
            'after_hp_check_date',
            //  治疗后检查方法
            'after_hp_check_method',
            // 治疗后检查方法输入
            'after_hp_check_method_input',
            //  治疗后检查结果
            'after_hp_check_result',
            //  治疗后-程度-上腹痛
            'after_post_degree_ep_pain',
            // 治疗后-程度-餐后饱张
            'after_post_degree_after_meal_satiety',
            //  治疗后-程度-早饱
            'after_post_degree_premature_satiety',
            // 治疗后-程度-上腹烧灼
            'after_post_degree_burn_upper_abdomen',
            // 治疗后-症状-总分
            'after_post_degree_amount',
            //治疗后-频率-上腹痛
            'after_post_frequency_ep_pain',
            // 治疗后-频率-餐后饱胀
            'after_post_frequency_after_meal_satiety',
            //  治疗后-频率-早饱
            'after_post_frequency_premature_satiety',
            // 治疗后-频率-上腹烧灼
            'after_post_frequency_burn_upper_abdomen',
            // 治疗后-频率-总分
            'after_post_frequency_amount',
            // 治疗后-其他-泛酸
            'after_other_acid_regurgitation',
            // 治疗后-其他-烧心
            'after_other_heartburn',
            // 治疗后-其他-大便
            'after_other_shit',
            // 治疗后-其他-疲乏
            'after_other_fatigued',
            //  治疗后-其他-睡眠差
            'after_other_poor_sleep',
            //  治疗后-其他-烦躁易怒
            'after_other_irritability',
            //  治疗后-其他-焦虑
            'after_other_anxiety',
            //  治疗后-其他-抑郁
            'after_other_depressed',
            // 是否产生不良反应 1是 2否
            'adversereaction',
            // 反应表现复选id
            'adversereaction_group',
            // 反应表现其他输入
            'adversereaction_group_input',
            // 日期
            'adversereaction_date',
            // 是否用药后立即发生 1是 2否
            'adversereaction_immediately',
            // 用药几小时
            'adversereaction_time_input',
            // 不良反应的严重程度单选id
            'adversereaction_degree',
            // 药物相关 单选id
            'adversereaction_related',
            // 邀请码
            'invitation_code',
            // 病例附件
            'attachments',
        ]);

        // $payload['medical_record_checkbox'] = ["1", "2", "3"];
        // $payload['adversereaction_group'] = ["1", "2", "3"];
        // dd(implode(',', $payload['symptom']));
        // 处理提交数组数据转成字符串
        // 用药记录复选框
        $payload['medical_record_checkbox'] = isset($payload['medical_record_checkbox']) && !empty($payload['medical_record_checkbox']) ? implode(',', $payload['medical_record_checkbox']) : '';
        // 不良反应复选id
        $payload['adversereaction_group'] = isset($payload['adversereaction_group']) && !empty($payload['adversereaction_group']) ? implode(',', $payload['adversereaction_group']) : '';


        $member = member();

        $payload['user_id'] = $member->userid;

        $id = $payload['id'];
        $invitation_code = isset($payload['invitation_code']) && !empty($payload['invitation_code']) ? $payload['invitation_code'] : '';

        unset($payload['id'], $payload['invitation_code']);
        if (isset($id) && $id != '') {
            $result = Medical::updateMedical($payload, $id);
            if ($result) {
                return success(['id' => $id]);
            } else {
                return fail_message();
            }
        } else {
            foreach ($payload as $key => &$val) {
                if (empty($val)) {
                    $val = '';
                }
            }
            $result = Medical::create($payload);
            if ($result) {
                $invitation = new InvitationCode();
                $invitation->useInvitationCode($invitation_code, $id);
                return success(['id' => $result->id]);
            } else {
                return fail_message();
            }
        }
    }

    /**
     * 检查邀请码
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-06-24
     * @param Request $request
     * @return void
     */
    public function checkCode(Request $request)
    {
        $rules = [
            'code' => ['required'],
        ];

        $message = [
            'code.required' => '请填写邀请码',
        ];

        $payload = $request->only('code');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        $invitation = new InvitationCode();
        $invitation->checkInvitationCode($payload['code'], '', 'create');
        return success();
    }
}
